<template>
  <div class="page-container">
    <!-- 步骤条开始 -->
    <steps :stepList="stepList" />
    <!-- 步骤条结束 -->
    <page-form :model="form" :rules="rules" layout="vertical" v-if="stepList[0].active">
      <!-- 订单基础信息 -->
      <div class="page-form-block" style="margin-bottom: 20px">
        <!-- 统计 -->
        <summary-info :summaryList="summaryLease" />
      </div>

      <card title="换下车信息" style="margin-top: 20px">
        <box-info :carId="orderInfo.carId" style="margin-bottom: 20px" />
        <page-form-row>
          <page-form-item label="换下车里程" field="returnCarMileage">
            <i-input-number :precision="0" unit="公里" v-model="form.returnCarMileage" />
          </page-form-item>
          <page-form-item label="换下车油(电)量" field="returnFuelNum">
            <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.returnFuelNum" />
          </page-form-item>
          <page-form-item field="replaceStaffId" label="换车人">
            <remote-select
              v-model="form.replaceStaffId"
              :params="{
                oldId: defaultStaffId ? defaultStaffId : undefined,
                siteIdList: [orderInfo.siteId],
              }"
              type="staff_authOrg"
            />
          </page-form-item>
          <page-form-item field="replaceTime" label="换车时间">
            <i-date-picker
              class="w-full"
              v-model="form.replaceTime"
              format="YYYY-MM-DD HH:mm"
              valueFormat="YYYY-MM-DD HH:mm:00"
              :disabled-date="disabledDate"
              :disabled-time="disabledTime"
              :time-picker-props="{
                format: 'HH:mm',
                defaultValue: '00:00',
              }"
              showTime
            />
          </page-form-item>
          <page-form-item label="换下车照片" size="1">
            <upload-img v-model="form.returnFileIds" />
          </page-form-item>
          <page-form-item label="换下车视频" size="1" class="mb-0">
            <upload-video v-model="form.returnVideoFileIds" :max="1" />
          </page-form-item>
        </page-form-row>
      </card>

      <card title="换上车信息" :showDivider="false" style="margin-top: 20px">
        <box-info :carId="form.carId" style="margin-bottom: 20px" />
        <page-form-row>
          <page-form-item label="车辆来源">
            <a-radio-group v-model="form.carSource" @change="changeCarSourceFn">
              <a-radio :value="item.value" v-for="(item, index) in dict.carSourceEnum" :key="index">{{ item.label }}</a-radio>
            </a-radio-group>
          </page-form-item>
          <page-form-item field="licenseNo" label="车牌号" labelTooltipContent="请选择换车时间后再进行排车">
            <i-input
              v-model="form.licenseNo"
              :disabled="!form.replaceTime"
              placeholder="请选择"
              :allow-clear="false"
              style="cursor: pointer"
              readonly
              icon="right"
              @click.stop="selectCarFn"
            />
          </page-form-item>
          <page-form-item label="排车车型" size="1"> {{ form.carModelName || '-' }} </page-form-item>
          <page-form-item label="换上车里程" size="1/3" field="giveCarMileage">
            <i-input-number :precision="0" unit="公里" v-model="form.giveCarMileage" />
          </page-form-item>
          <page-form-item label="换上车油(电)量" size="1/3" field="giveFuelNum">
            <i-input-number :precision="0" :min="1" :max="99999" unit="" v-model="form.giveFuelNum" />
          </page-form-item>
          <page-form-item label="换上车照片" size="1">
            <upload-img v-model="form.giveFileIds" />
          </page-form-item>
          <page-form-item label="换上车视频" size="1">
            <upload-video v-model="form.giveVideoFileIds" :max="1" />
          </page-form-item>
          <page-form-item label="换车备注" size="2/3">
            <i-textarea v-model="form.replaceRemark" />
          </page-form-item>
        </page-form-row>
      </card>
      <!-- 合同信息 -->
      <contract-card :showDivider="false" />
    </page-form>
    <!-- 订单费用信息 -->
    <div class="relative fee-pane-content" v-if="stepList[1].active">
      <page-form :model="feeForm" layout="vertical">
        <card title="换车费用" :showDivider="false">
          <template v-for="(item, index) in feeForm.orderFee" :key="index">
            <fee-pane :orderFeeIndex="index" :disabledOnlineFee="orderInfo.orderSource == 1" />
          </template>
        </card>
      </page-form>
    </div>
  </div>
  <!-- 底部 footer -->
  <page-form-footer hideCancel hideOk>
    <template v-if="stepList[0].active">
      <a-button key="close" @click="cancelFn">关闭</a-button>
      <a-button key="nextStep" type="primary" :disabled="!nextStepIsValid" @click="stepClickFn(stepList[1])">下一步</a-button>
    </template>
    <template v-if="stepList[1].active">
      <!-- <a-button>新增事故信息</a-button> -->
      <a-button key="addRepair" @click="newRepairFn">新增维修信息</a-button>
      <a-button key="addViolation" @click="newViolationFn">新增违章信息</a-button>
      <a-button key="prevStep" @click="stepClickFn(stepList[0])">上一步</a-button>
      <a-button key="submit" type="primary" :loading="okLoading" @click="submitFn">确认</a-button>
    </template>
  </page-form-footer>

  <!-- 选择车牌号 -->
  <car-selector :isLongOrder="true" ref="carSelectorRef" mode="select" @confirm="carConfirmFn" />
  <!-- 查询当前订单的换下车辆是否存在与当前订单关联的状态为已开始的ETC订单 -->
  <finishEtcOrderModal ref="etcModalRef" @ok="submitOperateFn" />
</template>

<script setup name="LongOrderChangeCar">
  import { ref, provide, computed, inject } from 'vue'
  import { useRoute, useRouter } from 'vue-router'
  import { usePageDict } from '@/hooks/useDict'
  import { Message } from '@arco-design/web-vue'
  import feePane from './components/order-fee/fee-pane.vue'
  import iTextarea from '@/views/order/long-order/components/i-textarea.vue'
  import summaryInfo from './components/summary-info.vue'
  import boxInfo from '../../business/workOrder/order/components/box-modal.vue'
  import dayjs from 'dayjs'
  import steps from './components/steps.vue'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'
  import carSelector from '@/views/assets/car/stock/car-selector.vue'
  import { getLongOrderDetails, replaceCar } from '@/api/order/czsOrder'
  import { checkExistEtcOrderApi } from '@/api/order/etcOrder'
  import finishEtcOrderModal from '../etc-order/components/finish-etc-order-modal.vue'
  import { getStoreTemplateDetail, initFeeDetail, buildCostInfoParam } from './components/order-fee/fee-utils.js'
  import contractCard from './components/contract/contract-card.vue'
  import { handleContracList } from './utils'
  const { navigateBack, navigateClose } = useNavigate()
  const dict = usePageDict('longOrderDict')
  const route = useRoute()
  const router = useRouter()
  const orderId = route.params.id
  const userStore = useUserStore()
  console.log('userStore', userStore)
  const orderInfo = ref({})
  const scrollbarRef = inject('scrollbarRef')
  // 滚动到顶部
  const scrollTopFn = () => {
    scrollbarRef && scrollbarRef.value.scrollTop(0)
  }
  // 步骤信息
  const stepList = ref([
    { stepText: '换车信息', stepNum: 1, active: true },
    { stepText: '费用信息', stepNum: 2, active: false },
  ])
  // rules
  const rules = ref({
    returnCarMileage: [{ required: true, message: '请输入换下车里程' }], // 换下车里程
    returnFuelNum: [{ required: true, message: '请输入换下车油(电)量' }], // 换下车油(电)量
    giveCarMileage: [{ required: true, message: '请输入换上车里程' }], // 换上车里程
    giveFuelNum: [{ required: true, message: '请输入换上车油(电)量' }], // 换上车油(电)量
    replaceStaffId: [{ required: true, message: '请选择换车人' }],
    replaceTime: [{ required: true, message: '请选择换车时间' }],
    licenseNo: { required: true, message: '请选择车牌号' },
  })

  // 默认员工
  const defaultStaffId = ref(userStore.employeeId)
  const form = ref({
    id: orderId,
    replaceTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    carSource: 1,
    replaceStaffId: defaultStaffId.value,
    contractList: [
      {
        contractFileId: '',
        contractNo: '',
        contractType: 2,
        contractTypeName: '换车合同',
        contractName: '',
        status: 'edit',
      },
    ],
    carLicenseNo: '',
  })
  const changeContractList = ref([])
  // 读取订单信息
  getLongOrderDetails({ id: orderId }).then((res) => {
    const result = res.result
    orderInfo.value = result.orderInfo
    form.value.orderCarId = orderInfo.value.useOrderCarId
    form.value.carId = orderInfo.value.carId
    form.value.siteId = orderInfo.value.siteId
    form.value.siteName = orderInfo.value.siteName
    form.value.originalModelId = orderInfo.value.originalModelId
    form.value.originalModelName = orderInfo.value.originalModelName
    form.value.expectedUseCarTime = orderInfo.value.expectedUseCarTime
    form.value.expectedReturnCarTime = orderInfo.value.expectedReturnCarTime
    form.value.leaseNumberStr = orderInfo.value.leaseNumberStr
    form.value.orderSourceName = orderInfo.value.orderSourceName
    orderInfo.value.startTime = orderInfo.value.expectedUseCarTime
    orderInfo.value.endTime = orderInfo.value.expectedReturnCarTime
    // 读取门店模板配置
    getStoreTemplateDetail(orderInfo.value.siteId, 2, (storeTemplate, templateId) => {
      // 更新费用模板 id
      priceTemplateId.value = templateId
      let feeValue = feeForm.value
      // 初始化费用
      initFeeDetail(feeValue, storeTemplate)
    })
    // 合同信息处理
    let orderContractList = orderInfo.value.contractList
    if (orderContractList && orderContractList.length > 0) {
      changeContractList.value = orderContractList.filter((item) => item.contractTypeName.indexOf('换车') !== -1)
      if (changeContractList.value.length == 0 || changeContractList.value.every((item) => item.contractFileId)) {
        changeContractList.value.push({
          contractFileId: '',
          contractNo: '',
          contractType: 2,
          contractTypeName: `换车合同${changeContractList.value.length + 1}`,
          contractName: '',
          status: 'edit',
        })
      }
    }
    form.value.contractList = handleContracList(changeContractList.value)
  })
  // 选择车牌
  const carSelectorRef = ref()
  const selectCarFn = () => {
    // 默认将换车时间作为开始时间，并同预计还车时间做比较
    // 1 若早于预计还车时间，则正常处理
    // 2 若晚于预计还车时间，则将实际开始时间设置为开始时间
    let startTime = form.value.replaceTime
    let endTime = orderInfo.value.expectedReturnCarTime
    if (dayjs(startTime).valueOf() > dayjs(endTime).valueOf()) {
      // 将开始时间设置为预计开始时间
      startTime = orderInfo.value.expectedUseCarTime
    }
    const param = {
      // siteId: orderInfo.value.siteId,
      modelId: orderInfo.value.originalModelId,
      dateRange: [startTime, endTime],
      id: form.value.carId,
      ...platoonModelQueryParam.value,
      carSource: form.value.carSource,
    }
    carSelectorRef.value.open(
      param,
      {
        ...orderInfo.value,
        modelId: orderInfo.value.originalModelId,
        platoonCarId: orderInfo.value.carId,
      },
      'long-order'
    )
  }
  const lastGiveCarTime = computed(() => {
    const orderCarInfos = orderInfo.value.longOrderCarInfoDtos
    let lastOrderCarInfo = {}
    if (orderCarInfos && orderCarInfos.length > 0) {
      lastOrderCarInfo = orderCarInfos[orderCarInfos.length - 1]
    }
    return lastOrderCarInfo.useStartTime
  })
  // disabled Date|Time
  const disabledDate = (dateVal) => {
    const prevDate = lastGiveCarTime.value
    if (!dateVal || !prevDate) {
      return false
    }
    // 存在限制最大范围
    // 当前时间是 23:50
    if (dayjs(prevDate).hour() == 23 && dayjs(prevDate).minute() == 59) {
      return dayjs(prevDate).add(1, 'd').startOf('day').valueOf() > dayjs(dateVal).valueOf()
    } else {
      return dayjs(prevDate).startOf('day').valueOf() > dayjs(dateVal).valueOf()
    }
  }
  const range = (start, end) => {
    const result = []
    for (let i = start; i < end; i++) {
      result.push(i)
    }
    return result
  }
  const disabledTime = (current) => {
    let options = {}
    let prevDate = lastGiveCarTime.value
    if (prevDate) {
      let currentTime = current ? dayjs(current) : dayjs()
      let currentTime_year = currentTime.year()
      let currentTime_month = currentTime.month()
      let currentTime_date = currentTime.date()
      let currentTime_hour = currentTime.hour()
      let prevDateTime = dayjs(prevDate)
      let prevDateTime_year = prevDateTime.year()
      let prevDateTime_month = prevDateTime.month()
      let prevDateTime_date = prevDateTime.date()
      let prevDateTime_hour = prevDateTime.hour()
      let prevDateTime_minute = prevDateTime.minute()
      if (prevDateTime_minute == 59) {
        options.disabledHours = () => range(0, prevDateTime_hour + 1)
        options.disabledMinutes = () => []
      } else {
        options.disabledHours = () => range(0, prevDateTime_hour)
        options.disabledMinutes = () => range(0, prevDateTime_minute + 1)
      }
      // 用户选择的是 未来 的天
      if (currentTime_year > prevDateTime_year || currentTime_month > prevDateTime_month || currentTime_date > prevDateTime_date) {
        options = {}
      } else {
        // 用户选择的是 未来 的小时
        if (currentTime_hour > prevDateTime_hour) {
          options.disabledMinutes = () => {
            return []
          }
        }
      }
    }
    return options
  }
  // 统计信息
  const summaryLease = computed(() => {
    const orderInfoVal = orderInfo.value
    return [
      [
        {
          label: '预计租赁周期',
          value: orderInfoVal.startTime ? `${orderInfoVal.startTime} - ${orderInfoVal.endTime}` : '-',
        },
        { label: '租期', value: orderInfoVal.leaseNumberStr },
        { label: '订单来源', value: orderInfoVal.orderSourceName },
      ],
      [
        { label: '订单获取方式', value: orderInfoVal.orderAcquisitionTypeName },
        { label: '预订车型', value: orderInfoVal.originalModelName },
        { label: '交车车型', value: orderInfoVal.modelName },
      ],
      [{ label: '交车车牌号', value: orderInfoVal.licenseNo }],
    ]
  })

  // 选择车牌完成后
  // 记录弹窗queryParam
  const platoonModelQueryParam = ref({})
  const carConfirmFn = (id, option = {}, queryParam) => {
    form.value.carId = id
    form.value.licenseNo = option.licenseNo
    form.value.carModelId = option.modelId
    form.value.carModelName = option.modelName

    // 记录弹窗queryParam
    platoonModelQueryParam.value = { ...queryParam }
  }

  // 切换订单来源
  const changeCarSourceFn = () => {
    form.value.carId = undefined
    form.value.licenseNo = undefined
    form.value.carModelId = undefined
    form.value.carModelName = undefined
    platoonModelQueryParam.value = {}
  }

  provide('form', form)
  provide('dict', dict)

  const priceTemplateId = ref()
  const feeForm = ref({
    randomKey: 0,
    orderFee: [
      {
        // 费用类型（线上费用|线下费用）
        feeType: 1,
        feeDetailList: [],
        priceTemplateId: priceTemplateId,
        feeDetailTypeList: ['extraFee'],
      },
    ],
  })
  provide('feeForm', feeForm)

  // 返回事件
  const cancelFn = () => {
    navigateClose()
  }
  // 确认事件
  const okLoading = ref(false)
  const submitOperateFn = () => {
    let feeFormValue = feeForm.value
    let costInfo = buildCostInfoParam(feeFormValue)
    form.value.carLicenseNo = form.value.licenseNo
    let param = {
      ...form.value,
      orderFee: costInfo.orderFee[0],
    }
    let contractList = form.value.contractList
    param.contractFileId = contractList[0].fileId
    param.contractNo = contractList[0].contractNo
    param.contractName = contractList[0].contractName
    okLoading.value = true
    replaceCar(param)
      .then((res) => {
        Message.success(res.result?.msg || res.message || '操作成功')
        navigateBack()
      })
      .finally(() => (okLoading.value = false))
  }
  // 检验换车车辆是否存在与当前订单关联的状态为已开始的ETC订单
  const etcModalRef = ref()
  const submitFn = () => {
    let params = {
      refType: 2,
      refId: form.value.id,
      carId: orderInfo.value.carId,
      endTime: form.value.replaceTime,
    }
    checkExistEtcOrderApi(params).then((res) => {
      let result = res.result
      if (result.existOrder) {
        let params = {
          carLicenseNo: orderInfo.value.licenseNo,
          operateStr: '换车',
        }
        etcModalRef.value.open(params)
      } else {
        submitOperateFn()
      }
    })
  }
  // 下一步是否可点击
  const nextStepIsValid = computed(() => {
    // 需要判断必填项是否均填写
    let formValue = form.value
    let requiredProp = ['replaceStaffId', 'replaceTime', 'licenseNo', 'returnCarMileage', 'returnFuelNum', 'giveCarMileage', 'giveFuelNum']
    return !requiredProp.some((item) => !formValue[item])
  })
  // 点击第二步、第一步事件
  const stepClickFn = (step) => {
    const { stepNum, active } = step
    if (!active) {
      if (stepNum == 2) {
        // 切换到 第2步的时候，需要校验第一步填写是否完成
        if (!nextStepIsValid.value) {
          return false
        }
      }
      // 触发跳转
      stepList.value.forEach((stepItem) => {
        stepItem.active = false
      })
      step.active = true
      scrollTopFn()
    }
  }
  const newRepairFn = () => {
    router.push(`/car-repair/create/${orderId}?page=longOrder`)
  }
  const newViolationFn = () => {
    router.push(`/car-violation/create/${orderId}?page=longOrder`)
  }
</script>

<style lang="less" scoped>
  .contContainer {
    margin-top: 25px;
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
    }
  }
</style>
